package me.zhenqu.redis;

import org.apache.commons.pool.BasePoolableObjectFactory;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

/**
 * Created at 11-7-5
 *
 * @author yonghui.chen
 */
public class PooledJedisFactory extends BasePoolableObjectFactory {
    private String host;
    private int port;
    private Logger logger = Logger.getLogger(getClass());

    public PooledJedisFactory(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public Object makeObject() throws Exception {
        final PooledJedis jedis;

        jedis = new PooledJedis(this.host, this.port);
        jedis.connect();
        logger.info("make a redis connection " + jedis.getKey());
        return jedis;
    }

    public void destroyObject(final Object obj) throws Exception {
        if (obj instanceof Jedis) {
            final PooledJedis jedis = (PooledJedis) obj;
            if (jedis.isConnected()) {
                try {
                    try {
                        logger.info("make a redis connection " + jedis.getKey());
                        jedis.quit();
                    } catch (Exception ignored) {
                    }
                    jedis.disconnect();
                } catch (Exception ignored) {

                }
            }
        }
    }

    public boolean validateObject(final Object obj) {
        if (obj instanceof PooledJedis) {
            final PooledJedis jedis = (PooledJedis) obj;
            try {
                return jedis.isValid() && jedis.isConnected() && jedis.ping().equals("PONG");
            } catch (final Exception e) {
                return false;
            }
        } else {
            return false;
        }
    }

}
